﻿using System;
using System.Drawing;
using System.Drawing.Imaging;

public class Texture
{
    public byte[] array;
    public int stride, width, height;
    public PixelFormat pf;

    public Texture(string name)
    {
        Bitmap texFile = (Bitmap)System.Drawing.Image.FromFile(name, true);
        pf = texFile.PixelFormat;
        BitmapData pmData = texFile.LockBits(new Rectangle(0, 0, texFile.Width, texFile.Height), ImageLockMode.ReadWrite, pf);

        IntPtr Scan0 = pmData.Scan0;
        array = new byte[pmData.Stride * pmData.Height];
        stride = pmData.Stride;
        width = pmData.Width;
        height = pmData.Height;
        System.Runtime.InteropServices.Marshal.Copy(Scan0, array, 0, array.Length);
        texFile.UnlockBits(pmData);
    }
    public LightIntensity GetPixel(int x, int y)
    {
        if (pf == PixelFormat.Format24bppRgb)
            return new LightIntensity(
                (double)array[x * 3 + 2 + y * stride]/255.0,
                (double)array[x * 3 + 1 + y * stride] / 255.0,
                (double)array[x * 3 + 0 + y * stride] / 255.0);
        if (pf == PixelFormat.Format32bppArgb)
            return new LightIntensity(
                (double)array[x << 2 + 2 + y * stride] / 255.0,
                (double)array[x << 2 + 1 + y * stride] / 255.0,
                (double)array[x << 2 + y * stride] / 255.0);
        return new LightIntensity(
            (double)array[x + y * stride] / 255.0,
            (double)array[x + y * stride] / 255.0,
            (double)array[x + y * stride] / 255.0);
    }
    public void SetPixel(int x, int y, LightIntensity col)
    {
        if (pf == PixelFormat.Format24bppRgb)
        {
            array[x * 3 + 2 + y * stride] = (byte)(col.r * 255);
            array[x * 3 + 1 + y * stride] = (byte)(col.g * 255);
            array[x * 3 + 0 + y * stride] = (byte)(col.b * 255);
        }
        else if (pf == PixelFormat.Format32bppArgb)
        {
            array[x << 2 + 3 + y * stride] = 255;
            array[x << 2 + 2 + y * stride] = (byte)(col.r * 255);
            array[x << 2 + 1 + y * stride] = (byte)(col.b * 255);
            array[x << 2 + 0 + y * stride] = (byte)(col.b * 255);
        }
    }
    public Vector2 ToUVRect(float x, float y)
    {
        float u, v;
        u = (x + (width / 2.0f)) / width;
        v = (y + (height / 2.0f)) / height;
        if (u > 1) u = 1;
        if (u < 0) u = 0;
        if (v > 1) u = 1;
        if (v < 0) u = 0;
        return new Vector2(u, v);
    }

    public LightIntensity rectMapping(float u, float v)
    {
        LightIntensity retColor;
        if (u < 0.04 && v < 0.04) retColor = new LightIntensity(1.0, 0.0, 0.0);
        else retColor = GetPixel((int)((width - 1) * u), (int)((height - 1) * v));
        //retColor = GetPixel((int)((width - 1) * u), (int)((height - 1) * v));
        return retColor;
    }
    
}
